package com.niguang.labour.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhenJin
 */
public class IpUtils {

    private final static String UNKNOWN = "unknown";
    private final static String LOCAL_IP = "127.0.0.1";

    /**
     * @describe：获取IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("X-Forwarded-For");

        if (StringUtils.isBlank(ip) || (LOCAL_IP.equals(ip)) || UNKNOWN.equals(ip)) {
            ip = request.getHeader("X-Real-IP");

            if (StringUtils.isBlank(ip) || (LOCAL_IP.equals(ip)) || UNKNOWN.equals(ip)) {
                ip = request.getHeader("Proxy-Client-IP");

                if (StringUtils.isBlank(ip) || (LOCAL_IP.equals(ip)) || UNKNOWN.equals(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");

                    if (StringUtils.isBlank(ip) || (LOCAL_IP.equals(ip)) || UNKNOWN.equals(ip)) {
                        ip = request.getRemoteAddr();
                    }
                }
            }
        }

        // 多个IP地址时获取第一个IP
        if (StringUtils.isNotBlank(ip) && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}


